package developer.算法.二叉树.二叉树展开为链表;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhangyongkang
 * @time 2025/3/26 11:05
 * @description 给你二叉树的根结点 root ，请你将它展开为一个单链表：
 * <p>
 * 展开后的单链表应该同样使用 TreeNode ，其中 right 子指针指向链表中下一个结点，而左子指针始终为 null 。
 * 展开后的单链表应该与二叉树 先序遍历 顺序相同。
 * <p>
 * 输入：root = [1,2,5,3,4,null,6]
 * 输出：[1,null,2,null,3,null,4,null,5,null,6]
 */
public class ErChaShuZhanKaiWeiLianBIao {

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     * int val;
     * TreeNode left;
     * TreeNode right;
     * TreeNode() {}
     * TreeNode(int val) { this.val = val; }
     * TreeNode(int val, TreeNode left, TreeNode right) {
     * this.val = val;
     * this.left = left;
     * this.right = right;
     * }
     * }
     */
    public static void main(String[] args) {
        SolutionSelf solution = new SolutionSelf();
        TreeNode treeNode = new TreeNode(1, new TreeNode(2, new TreeNode(3), new TreeNode(4)), new TreeNode(5, null, new TreeNode(6)));
        solution.flatten(treeNode);
    }

    static class SolutionSelf {
        public void flatten(TreeNode root) {
            TreeNode treeNode = new TreeNode();
            TreeNode current = treeNode;
            List<TreeNode> treeNodes = new ArrayList<>();
            qianXuBianLi(root, treeNodes);


            for (TreeNode node : treeNodes) {
                current.left = null;
                current.right = node;
                current = current.right;
            }
            root = treeNode.right;
            System.out.println(root);
        }

        public void qianXuBianLi(TreeNode root, List<TreeNode> list) {
            if (root == null) return;
            list.add(root);
            qianXuBianLi(root.left, list);
            qianXuBianLi(root.right, list);
        }
    }

    class SolutionOfficial {
        public void flatten(TreeNode root) {
            TreeNode curr = root;
            while (curr != null) {
                if (curr.left != null) {
                    TreeNode next = curr.left;
                    TreeNode predecessor = next;
                    while (predecessor.right != null) {
                        predecessor = predecessor.right;
                    }
                    predecessor.right = curr.right;
                    curr.left = null;
                    curr.right = next;
                }
                curr = curr.right;
            }
        }
    }


    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
